package libs

import (
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

func handleCreateOrModify(path string, isCreate bool) {
	fileInfo, err := os.Stat(path)
	if err != nil {
		DebugPrint("获取文件信息失败: %v\n", err)
		return
	}

	isDir := fileInfo.IsDir()

	if isDir && !isCreate {
		return // 忽略目录的修改事件
	}

	maxSize, err := parseSize(Config.MaxLimitSize)
	if err != nil {
		DebugPrint("解析最大文件大小失败: %v\n", err)
		return
	}

	if fileInfo.Size() > maxSize {
		DebugPrint("文件 %s 超过大小限制\n", path)
		return
	}

	sendFileToRemote(path, isDir, isCreate)

}

func isIgnored(path string) bool {
	for _, ignorePath := range Config.IgnoreList {
		if strings.Contains(path, ignorePath) {
			return true
		}
	}

	for _, pattern := range Config.IgnorePatterns {
		if strings.Contains(path, pattern) {
			return true
		}
	}

	return false
}

func parseSize(sizeStr string) (int64, error) {
	sizeStr = strings.ToUpper(sizeStr)
	multiplier := int64(1)

	if strings.HasSuffix(sizeStr, "KB") {
		multiplier = 1024
		sizeStr = strings.TrimSuffix(sizeStr, "KB")
	} else if strings.HasSuffix(sizeStr, "MB") {
		multiplier = 1024 * 1024
		sizeStr = strings.TrimSuffix(sizeStr, "MB")
	} else if strings.HasSuffix(sizeStr, "GB") {
		multiplier = 1024 * 1024 * 1024
		sizeStr = strings.TrimSuffix(sizeStr, "GB")
	}

	size, err := strconv.ParseInt(strings.TrimSpace(sizeStr), 10, 64)
	if err != nil {
		return 0, err
	}

	return size * multiplier, nil
}

func isDir(path string) bool {
	info, err := os.Stat(path)
	if err != nil {
		return false
	}
	return info.IsDir()
}

func handleRenameEvent(oldPath string) {

	renameMutex.Lock()
	defer renameMutex.Unlock()

	lastRename.oldPath = oldPath
	lastRename.time = time.Now()
}

func isRelatedToRename(newPath string) bool {
	renameMutex.Lock()
	defer renameMutex.Unlock()

	if time.Since(lastRename.time) > time.Second {
		return false
	}

	return filepath.Dir(newPath) == filepath.Dir(lastRename.oldPath)
}

func handleRenameCompletion(newPath string) {
	renameMutex.Lock()
	oldPath := lastRename.oldPath
	renameMutex.Unlock()

	if strings.Contains(lastRename.oldPath, "---") {
		return // 如果oldPath包含"---"，则忽略此重命名事件
	}
	sendRenameRequestToRemote(oldPath, newPath)
}

func uploadDirectory(dirPath string) {
	err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			sendFileToRemote(path, false, true)
		}
		return nil
	})
	if err != nil {
		DebugPrint("上传目录失败: %v\n", err)
	}
}
